package com.github.postsanf.yinian.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.bean.YNUserStoragePlace;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.fragment.MineFragement;
import com.github.postsanf.yinian.utils.UIHelper;
import com.github.postsanf.yinian.utils.YNInviteSecret;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.LinkedHashMap;

/**
 * 我的空间
 */
public class AwardActivity extends BaseActivity implements View.OnClickListener {
    private TextView zongSize;
    private TextView useSize;
    private TextView remainSize;
    private TextView tv_invite;
    private ImageView invite_get;
    private TextView tv_qiandao;
    private ImageView qiandao_get;
    private ImageView share_get;
    private ImageView loginweb_get;
    private RelativeLayout kuorong_top_air;
    private RelativeLayout kuorong_buttom_air;
    private ProgressBar kuorong_progressbar;
    private int uInviteReward;
    private int uCreateReward;
    private int uJoinReward;
    private String shareTitle = "推荐丨忆年-零负担亲密社交圈，一起记录美好生活！";
    private String shareContent = "和家人/闺蜜/同事/爱人一起分享照片，原图上传，云端永久储存。还能上传语音、文字和地理位置！时间多美，让我们开启忆年!";
    private UMShareAPI mShareAPI;
    int appInvite = 0;
    int appInviteNum = 0;
    int appSign = 0;
    int signDay = 0;
    int appShareMoments = 0;
    int appLoginWeb = 0;
    boolean isTodaySign;
    private String inviteUrl;
    private String inviteKey;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_award);
        mShareAPI = UMShareAPI.get(this);
        doInvateKey();
        initView();
    }

    private void doInvateKey() {
        String invite = CommonConstants.YNS_USER_ID + "=" + application.getCurID();
        try {
            inviteKey = YNInviteSecret.encryptDES(invite, getString(R.string.UNKNOW_ID));
        } catch (Exception e) {
            e.printStackTrace();
        }
        inviteUrl = "http://wx.zhuiyinanian.com/app/inviteFriendFromUser.html?code=" + inviteKey;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mShareAPI.onActivityResult(requestCode, resultCode, data);
    }

    private void initView() {
        kuorong_progressbar = (ProgressBar) findViewById(R.id.kuorong_progressbar);
        zongSize = (TextView) findViewById(R.id.zong_size);
        remainSize = (TextView) findViewById(R.id.remain_size);
        useSize = (TextView) findViewById(R.id.use_size);
        tv_invite = (TextView) findViewById(R.id.tv_invite);
        invite_get = (ImageView) findViewById(R.id.invite_get);
        tv_qiandao = (TextView) findViewById(R.id.tv_qiandao);
        qiandao_get = (ImageView) findViewById(R.id.qiandao_get);
        share_get = (ImageView) findViewById(R.id.share_get);
        loginweb_get = (ImageView) findViewById(R.id.loginweb_get);
        kuorong_top_air = (RelativeLayout) findViewById(R.id.kuorong_top_air);
        kuorong_buttom_air = (RelativeLayout) findViewById(R.id.kuorong_buttom_air);
        findViewById(R.id.iv_back).setOnClickListener(this);
        useSize.setOnClickListener(this);
        invite_get.setOnClickListener(this);
        qiandao_get.setOnClickListener(this);
        share_get.setOnClickListener(this);
        loginweb_get.setOnClickListener(this);
        initGetSpace();
        ShowExpandSpacePage();
    }

    private void updateProgress(int progress) {
        kuorong_progressbar.setProgress(progress);
        int useW = UIHelper.dip2px(this, 240) * progress / 100;
        int remainW = UIHelper.dip2px(this, 240) - useW;
//        TranslateAnimation translateAnimation = new TranslateAnimation(0, useW + remainW / 2 - UIHelper.dip2px(this, 32), 0, 0);
//        translateAnimation.setDuration(800);
//        translateAnimation.setFillAfter(true);
//        kuorong_top_air.startAnimation(translateAnimation);
//        TranslateAnimation translateAnimationbuttom = new TranslateAnimation(0, useW / 2 - UIHelper.dip2px(this, 29), 0, 0);
//        translateAnimationbuttom.setDuration(800);
//        translateAnimationbuttom.setFillAfter(true);
//        kuorong_buttom_air.startAnimation(translateAnimationbuttom);
        RelativeLayout.LayoutParams toplps = (RelativeLayout.LayoutParams) kuorong_top_air.getLayoutParams();
        toplps.setMargins(useW + remainW / 2 - UIHelper.dip2px(this, 32), 0, 0, 0);
        RelativeLayout.LayoutParams btmlps = (RelativeLayout.LayoutParams) kuorong_buttom_air.getLayoutParams();
        btmlps.setMargins(useW / 2 - UIHelper.dip2px(this, 29), UIHelper.dip2px(this, 2), 0, 0);
    }

    private void ShowExpandSpacePage() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, application.getCurID() + "");
        StringRequest req = new StringRequest("https://api.zhuiyinanian.com/YinianProject/activity/ShowExpandSpacePage")
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>() {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        Log.i("xjs", "s==>" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if (jsonObject.optInt("code") == 0) {
                                //  0—未领取 1—可领取    2—已领取
                                isTodaySign = jsonObject.optJSONArray("data").optJSONObject(0).optBoolean("isTodaySign");
                                appInviteNum = jsonObject.optJSONArray("data").optJSONObject(0).optInt("appInviteNum");
                                appInvite = jsonObject.optJSONArray("data").optJSONObject(0).optInt("appInvite");
                                signDay = jsonObject.optJSONArray("data").optJSONObject(0).optInt("signDay");
                                appSign = jsonObject.optJSONArray("data").optJSONObject(0).optInt("appSign");
                                appShareMoments = jsonObject.optJSONArray("data").optJSONObject(0).optInt("appShareMoments");
                                appLoginWeb = jsonObject.optJSONArray("data").optJSONObject(0).optInt("appLoginWeb");
                                tv_invite.setText(UIHelper.getTextNumInvite(AwardActivity.this, "邀请好友注册•奖励9GB(" + appInviteNum + "/3)"));
                                tv_qiandao.setText(UIHelper.getTextNumInvite(AwardActivity.this, "连续签到一周•奖励3GB(" + signDay + "/7)"));
                                switch (appInvite) {
                                    case 0:
                                        invite_get.setImageResource(R.drawable.kuorong_btn_invite);
                                        break;
                                    case 1:
                                        invite_get.setImageResource(R.drawable.kuorong_btn_get);
                                        break;
                                    case 2:
                                        invite_get.setImageResource(R.drawable.kuorong_btn_isgetyes);
                                        break;
                                }
                                switch (appSign) {
                                    case 0:
                                        if (isTodaySign) {
                                            qiandao_get.setImageResource(R.drawable.kuorong_btn_isqiandaoget);
                                        } else {
                                            qiandao_get.setImageResource(R.drawable.kuorong_btn_qiandao);
                                        }
                                        break;
                                    case 1:
                                        qiandao_get.setImageResource(R.drawable.kuorong_btn_get);
                                        break;
                                    case 2:
                                        qiandao_get.setImageResource(R.drawable.kuorong_btn_isgetyes);
                                        break;
                                }
                                switch (appShareMoments) {
                                    case 0:
                                        share_get.setImageResource(R.drawable.kuorong_btn_share);
                                        break;
                                    case 1:
                                        share_get.setImageResource(R.drawable.kuorong_btn_get);
                                        break;
                                    case 2:
                                        share_get.setImageResource(R.drawable.kuorong_btn_isgetyes);
                                        break;
                                }
                                switch (appLoginWeb) {
                                    case 0:
                                        loginweb_get.setImageResource(R.drawable.kuorong_btn_loginweb);
                                        break;
                                    case 1:
                                        loginweb_get.setImageResource(R.drawable.kuorong_btn_get);
                                        break;
                                    case 2:
                                        loginweb_get.setImageResource(R.drawable.kuorong_btn_isgetyes);
                                        break;
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    //获取我的空间和已使用空间
    private void initGetSpace() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, application.getCurID() + "");
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynGetUserData))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>() {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNUserStoragePlace userStoragePlace = gson.fromJson(s, YNUserStoragePlace.class);
                        if (userStoragePlace.getData().size() != 0) {
                            double totalSpaceToGB = getSpaceToGB(userStoragePlace.getData().get(0).getUtotalspace());
                            double useSpaceToGB = getSpaceToGB(userStoragePlace.getData().get(0).getUusespace());
                            DecimalFormat totalFormat = new DecimalFormat("####.00");//四舍五入不保留小数
                            zongSize.setText(totalFormat.format(totalSpaceToGB) + "G");
                            useSize.setText(getSpaceToGBOrMB(userStoragePlace.getData().get(0).getUusespace()));
                            remainSize.setText(getSpaceToGBOrMB(userStoragePlace.getData().get(0).getUtotalspace() - userStoragePlace.getData().get(0).getUusespace()));
                            String format = new DecimalFormat("#").format((useSpaceToGB / totalSpaceToGB) * 100);
                            updateProgress(Integer.parseInt(format));
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    //签到
    private void AppSignIn() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, application.getCurID() + "");
        StringRequest req = new StringRequest("https://api.zhuiyinanian.com/YinianProject/activity/AppSignIn")
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>() {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        Log.i("xjs", "qiandao==>" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if (jsonObject.optInt("code") == 0) {
                                showToast("签到成功");
                                ShowExpandSpacePage();
                            } else {
                                showToast(jsonObject.optString("msg"));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }


    private double getSpaceToGB(double totalSpace) {
        double totalSpcaeGB = totalSpace / 1024 / 1024;
        return totalSpcaeGB;
    }

    private String getSpaceToGBOrMB(double totalSpace) {
        if (totalSpace > 1024 * 1024) {
            DecimalFormat useFormat = new DecimalFormat("###0.00");//四舍五入不保留小数
            return useFormat.format(totalSpace / 1024 / 1024) + "G";
        } else {
            DecimalFormat useFormat = new DecimalFormat("#");//四舍五入不保留小数
            return useFormat.format(totalSpace / 1024) + "M";
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.invite_get:
                switch (appInvite) {
                    case 0:
                        //邀请
                        UMWeb web = new UMWeb(inviteUrl);
                        web.setTitle(shareTitle);
                        web.setThumb(new UMImage(AwardActivity.this, MineFragement.avatarPic));
                        web.setDescription(shareContent);
                        new ShareAction(this).setPlatform(SHARE_MEDIA.WEIXIN).setCallback(InviteShareListener)
                                .withMedia(web)
                                .share();
                        break;
                    case 1:
                        getSpace("invite");
                        break;
                }
                break;
            case R.id.qiandao_get:
                switch (appSign) {
                    case 0:
                        AppSignIn();
                        break;
                    case 1:
                        getSpace("sign");
                        break;
                }
                break;
            case R.id.share_get:
                switch (appShareMoments) {
                    case 0:
                        UMWeb web = new UMWeb(inviteUrl);
                        web.setTitle(shareTitle);//标题
                        web.setThumb(new UMImage(AwardActivity.this, MineFragement.avatarPic));  //缩略图
                        web.setDescription(shareContent);//描述
                        new ShareAction(this).setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE).setCallback(umShareListener)
                                .withMedia(web)
                                .share();
                        break;
                    case 1:
                        getSpace("share");
                        break;
                }
                break;
            case R.id.loginweb_get:
                switch (appLoginWeb) {
                    case 0:
                        startActivity(new Intent(AwardActivity.this, PcIntroduceActivity.class));
                        break;
                    case 1:
                        getSpace("login");
                        break;
                }
                break;
        }
    }


    private UMShareListener InviteShareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {
        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            if (platform.name().equals("WEIXIN_FAVORITE")) {
                Toast.makeText(AwardActivity.this, platform + " 收藏成功啦", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(AwardActivity.this, platform + " 分享成功啦", Toast.LENGTH_SHORT).show();
                Log.i("xjs", "InviteShareListener==>");
                ShowExpandSpacePage();
            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(AwardActivity.this, platform + " 分享失败啦", Toast.LENGTH_SHORT).show();
            if (t != null) {
                com.umeng.socialize.utils.Log.d("throw", "throw:" + t.getMessage());
            }
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(AwardActivity.this, platform + " 分享取消了", Toast.LENGTH_SHORT).show();
        }
    };
    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {
        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            if (platform.name().equals("WEIXIN_FAVORITE")) {
                Toast.makeText(AwardActivity.this, platform + " 收藏成功啦", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(AwardActivity.this, platform + " 分享成功啦", Toast.LENGTH_SHORT).show();
                Log.i("xjs", "umShareListener==>");
                AchieveGetSpaceCondition();
            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(AwardActivity.this, platform + " 分享失败啦", Toast.LENGTH_SHORT).show();
            if (t != null) {
                com.umeng.socialize.utils.Log.d("throw", "throw:" + t.getMessage());
            }
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(AwardActivity.this, platform + " 分享取消了", Toast.LENGTH_SHORT).show();
        }
    };

    //分享成功满足领奖条件
    private void AchieveGetSpaceCondition() {
        Log.i("xjs", "AchieveGetSpaceCondition==>");
        final LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        mParam.put(CommonConstants.YNS_TYPE, "share");
        StringRequest req = new StringRequest("https://api.zhuiyinanian.com/YinianProject/activity/AchieveGetSpaceCondition")
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>() {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        Log.i("xjs", "onSuccessd对==>");
                        ShowExpandSpacePage();
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        Log.i("xjs", "AppSuccessInviteccccccccccccc错我==>");
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    //用户领取奖励
    private void getSpace(final String type) {
        final LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        mParam.put(CommonConstants.YN_AWARDTYPE_TYPE, type);
        StringRequest req = new StringRequest("https://api.zhuiyinanian.com/YinianProject/activity/GetReward")
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>() {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        initGetSpace();
                        ShowExpandSpacePage();
                        sendBroadcast(new Intent("updateRongLiangShow"));
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }


    private long fristTime;

    // 友盟统计
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
        fristTime = System.currentTimeMillis();
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
        Intent intent = new Intent(ACTIONs.record);
        intent.putExtra("key", "我的空间_3");
        intent.putExtra("value", new Long(System.currentTimeMillis() - fristTime).intValue());
        sendBroadcast(intent);
    }
}
